/*
 * Utils.java
 *
 * Created on 14 March 2007, 02:41
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package net.siit.text;

import net.siit.datatype.Range;
import java.io.*;
import java.util.*;
import net.siit.util.*;

/**
 *
 * @author art
 */
public class TextUtil {

    /** Creates a new instance of Utils */
    public TextUtil() {
    }

    public static String toString(List<String> lines) {
        StringBuffer text = new StringBuffer();
        for (String line : lines) {
            text.append(line);
            text.append('\n');
        }
        return text.toString();
    }

    public static List<String> toList(InputStream input, String charset) {
        List<String> list = new ArrayList<String>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset));
            String str;
            while ((str = reader.readLine()) != null) {
                str = str.trim();
                if (str.length() > 0)
                    list.add(str);
            }
            if (reader != null)
                reader.close();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        Collections.sort(list);
        return list;
    }

    public static List<String> toList(String text) {
        List<String> list = new ArrayList<String>();

        try {
            BufferedReader reader = new BufferedReader(new StringReader(text));
            String str;
            while ((str = reader.readLine()) != null) {
                str = str.trim();
                if (str.length() > 0)
                    list.add(str);
            }
            if (reader != null)
                reader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        Collections.sort(list);
        return list;
    }

    public static void save(String text, String outFilename, String charset) {
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilename), charset));
            writer.append(text);
            writer.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String load(String inFilename, String charset) {
        StringBuffer text = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inFilename), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
            if (reader != null)
                reader.close();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return text.toString();
    }

    public static String compact(String text) {
        StringBuffer newText = new StringBuffer();
        BufferedReader reader = new BufferedReader(new StringReader(text));
        try {
            String str;
            while ((str = reader.readLine()) != null) {
                newText.append(str.trim());
                newText.append('\n');
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return newText.toString();
    }

    public static String mark(String text, List<Range> ranges, String openMark, String closeMark) {
        StringBuffer newText = new StringBuffer();
        for (Range range : ranges) {
            newText.append(text.substring(0, range.getStart()));
            newText.append(openMark);
            newText.append(text.substring(range.getStart(), range.getEnd()));
            newText.append(closeMark);
            text = text.substring(range.getEnd());
        }
        return newText.append(text).toString();
    }

    /**
     *
     * @param text
     * @param words
     * @return
     */
    public static List<Range> matchWords(String text, List<String> words) {
        // 1) choose the match that closest to the string starting point
        // 2) if matches share a starting point, chose the longest match
        // (choosing logic embedded in Range#compareTo)

        List<Range> ranges = new ArrayList<Range>();
        List<Range> candidates;

        int begin = -1;
        int end   = -1;
        boolean found;
        while (text.length() > 0) {
            found = false;
            candidates = new ArrayList<Range>();
            for (String word : words) {
                if ((begin = text.indexOf(word)) != -1) {
                    candidates.add(new Range(begin, begin + word.length()));
                    found = true;
                }
            }
            if (!found) { // not found
                return ranges; // don't sort this!
            } else { // found
                Collections.sort(candidates);
                Range range = candidates.get(0);
                ranges.add(new Range(range.getStart(), range.getEnd()));
                end = range.getEnd();
                //indexes.add(candidates.get(0));
            }
            text = text.substring(end);
        }

        return ranges; // don't sort this!
    }

    /**
     * Remove all spaces in a string
     */
    public static String removeSpaces(String name) {
        StringBuffer newName = new StringBuffer();
        int len = name.length();
        for (int i = 0; i < len; i++) {
            char c = name.charAt(i);
            if (! Character.isWhitespace(c) )
                newName.append(c);
        }

        return newName.toString();
    }

    /**
     * Remove all repeated spaces in a string
     */
    public static String removeRepeatedSpaces(String text) {
        StringBuffer newText = new StringBuffer();
        int len = text.length();
        boolean prevIsSpace = false;

        for (int i = 0; i < len; i++) {
            char c = text.charAt(i);
            if (Character.isWhitespace(c) ) {
                if (prevIsSpace) {
                    continue;
                } else {
                    newText.append(c);
                }
            } else {
                newText.append(c);
                prevIsSpace = false;
            }
        }

        return newText.toString();
    }

}
